package com.zh.kotlin_mvvm.utils

import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

class OutNetWorkUtils {

    //获取外网IP接口
    private val GET_IP = "https://ifconfig.co/json"

    //修正（2018-06-27）：上边的ifconfig国内已经登录不上，查找后重新找到了可用的地址
//  private val GET_IP = "https://ip.chinaz.com/getip.aspx"
//  private val GET_IP = "https://www.3322.org/dyndns/getip"
    fun FragmentActivity.getNetworkIp2(){
        this.lifecycleScope.launch {
            var infoUrl: URL? = null
            var inStream: InputStream? = null
            try {
                infoUrl = URL(GET_IP)
                val connection = infoUrl.openConnection()
                val httpConnection = connection as HttpURLConnection
                connection.setConnectTimeout(2000)
                connection.setReadTimeout(2000)
                val responseCode = httpConnection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    inStream = httpConnection.inputStream
                    val reader = BufferedReader(InputStreamReader(inStream, "utf-8"))
                    val strber = StringBuilder()
                    var line: String? = null
                    while (reader.readLine().also { line = it } != null) strber.append(
                        "$line".trimIndent()
                    )
                    inStream.close()
                    val jsonObject = JSONObject(strber.toString())
                    //从反馈的结果中提取出IP地址
                     jsonObject.getString("ip")
                }
            } catch (e: Exception) {
                 "127.0.0.1"
            }
             "127.0.0.1"
        }
    }
}